package com.totoro.tygeneratedragonblock.executor.drop.impl;

import com.totoro.tygeneratedragonblock.data.ComputeResult;
import com.totoro.tygeneratedragonblock.executor.drop.DropExecutor;
import com.totoro.tygeneratedragonblock.utils.ProbabilityUtil;
import io.lumine.xikage.mythicmobs.MythicMobs;
import io.lumine.xikage.mythicmobs.items.ItemManager;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.util.Map;

/**
 * @author Totoro
 * @version 0.1.0
 * @date 2025/8/10 - 22:00
 * @description
 **/
public class MythicMobsDropExecutor implements DropExecutor {
    @Override
    public void execute(Map<String, ComputeResult> parseValueMap, Player player, String drop, Location location) {
        // 开始分割，格式为mm#物品名#数量#概率
        String[] split = drop.split("#");
        if(split.length != 4) {
            return;
        }
        String itemName = split[1];
        // 获取ItemStack
        ItemManager itemManager = MythicMobs.inst().getItemManager();
        ItemStack itemStack = itemManager.getItemStack(itemName);
        // 为null直接返回不操作
        if(null == itemStack) {
            return;
        }
        // 将itemStack数量设为1，目的是模拟最真实的掉落
        itemStack.setAmount(1);

        // 解析概率规则：如果概率是isSuccess不为空直接使用，如果为空那就再计算一次概率
        String probability = split[3];
        boolean success;
        if(parseValueMap.containsKey(probability)) {
            ComputeResult computeResult = parseValueMap.get(probability);
            if(computeResult.getIsSuccess() != null) {
                success = computeResult.getIsSuccess();
            } else {
                success = ProbabilityUtil.checkSuccess(computeResult.getResult().doubleValue());
            }
        } else {
            success = ProbabilityUtil.checkSuccess(Double.parseDouble(probability));
        }
        if(success) {
            // 获取数量并解析
            String amount = split[2];
            if(parseValueMap.containsKey(amount)) {
                amount = amount.replace(amount, parseValueMap.get(amount).getResult().toString());
            }
            // 获取最终数量
            int finalAmount = Double.valueOf(amount).intValue();
            for (int i = 0; i < finalAmount; i++) {
                location.getWorld().dropItem(location, itemStack);
            }
        }

    }
}
